package com.xxxx.server.service.impl;

import java.io.File;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.xxxx.server.exceptions.MyException;
import com.xxxx.server.mapper.AdminMapper;
import com.xxxx.server.pojo.vo.MailVo;
import com.xxxx.server.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.mail.internet.MimeMessage;

@Component
public class MailServiceImpl implements MailService {
 
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private AdminMapper adminMapper;
 
    @Autowired
    private JavaMailSenderImpl mailSenderImp;//注入邮件工具类

    @Autowired
    private RedisTemplate redisTemplate;
    
    // 注入常量用户名
    @Value("${spring.mail.username}")
    private String from;
    
    /**
     	* 发送文本邮件
     * @param email
     */
    @Override
    public void getEmailCode(String email) {
        //生成六位数邮箱验证码
        Random random = new Random();
        Integer emailCode = random.nextInt(899999) + 100000;

        // 纯文本邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email.split(","));
        message.setSubject("TIM邀请您找回密码！");
        message.setText("TIM验证码："+emailCode);
 
        try {
            redisTemplate.opsForValue().set(email,emailCode.toString(),60*5, TimeUnit.SECONDS);
            mailSender.send(message);
            logger.info("Text邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送Text邮件时发生异常！\n", e);
            throw new MyException(e.getMessage());
        }
    }
 
    /**
     * 发送html邮件
     */
    @Override
    public void sendHtmlMail(MailVo vo) {
        // html 邮件对象
        MimeMessage message = mailSender.createMimeMessage();
 
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(vo.getTo().split(","));
            helper.setSubject(vo.getSubject());
            helper.setText(vo.getText(), true);
 
            mailSender.send(message);
            logger.info("html邮件发送成功");
        } catch (MessagingException | javax.mail.MessagingException e) {
            logger.error("发送html邮件时发生异常！", e);
        }
    }
 
 
    /**
     * 发送带附件的邮件
     */
    public void sendAttachmentsMail(MailVo vo){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(vo.getTo().split(","));
            helper.setSubject(vo.getSubject());
            helper.setText(vo.getText(), true);
 
            FileSystemResource file = new FileSystemResource(new File(vo.getFilePath()));
            String fileName = vo.getFilePath().substring(vo.getFilePath().lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            //helper.addAttachment("test"+fileName, file);
 
            mailSender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException | javax.mail.MessagingException e) {
            logger.error("发送带附件的邮件时发生异常！", e);
        }
    }
 
 
    /**
     * 发送正文中有静态资源（图片）的邮件
     */
    public void sendInlineResourceMail(MailVo vo){
        MimeMessage message = mailSender.createMimeMessage();
 
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(vo.getTo().split(","));
            helper.setSubject(vo.getSubject());
            helper.setText(vo.getText(), true);
 
            FileSystemResource res = new FileSystemResource(new File(vo.getRscPath()));
            helper.addInline(vo.getRscId(), res);
 
            mailSender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException | javax.mail.MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常！", e);
        }
    }
    
    //获取邮件发信人
    public String getMailSendFrom() {
        return mailSenderImp.getJavaMailProperties().getProperty("from");
    }
    
}